package com.ruoyi.common.utils.http;


import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.HttpResponseResult;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * HttpClient发送GET、POST请求
 */
public class HttpsUtils {

    private static final Logger log = LoggerFactory.getLogger(HttpsUtils.class);
    /*
     * 返回成功状态码
     */
    private static final int SUCCESS_CODE = 200;

    /*
     * 代理失效状态码
     */
    private static final int NO_BALANCE = 701;//No Balance 用户余额不足（提取按量版余额不足）
    private static final int NO_BIND_IP = 702;//No BindIP 绑定ip已过期
    private static final int NOT_WHITE_IP = 704;//NOT WhiteIp 请求ip不是白名单

    public static HttpResponseResult sendGet(String url, List<NameValuePair> nameValuePairList, Map<String, Object> requestPropertyMap) {
        return sendGet(url,nameValuePairList,requestPropertyMap,null,0);
    }

    public static HttpResponseResult sendPost(String url, List<NameValuePair> nameValuePairList, Map<String, Object> requestPropertyMap) {
        return sendPost(url,nameValuePairList,null,requestPropertyMap,null,0);
    }
    public static HttpResponseResult sendPost(String url, String jsonParams, Map<String, Object> requestPropertyMap) {
        return sendPost(url,null,jsonParams,requestPropertyMap,null,0);
    }

    public static HttpResponseResult proxySendGet(String url, Map<String, Object> requestPropertyMap) {
        return sendGet(url,null,requestPropertyMap,proxyHost,proxyPort);
    }
    public static HttpResponseResult proxySendGet(String url, List<NameValuePair> nameValuePairList, Map<String, Object> requestPropertyMap) {
        return sendGet(url,nameValuePairList,requestPropertyMap,proxyHost,proxyPort);
    }

    public static HttpResponseResult proxySendPost(String url, Map<String, Object> requestPropertyMap) {
        return sendPost(url,null,null,requestPropertyMap,proxyHost,proxyPort);
    }
    public static HttpResponseResult proxySendPost(String url, List<NameValuePair> nameValuePairList, Map<String, Object> requestPropertyMap) {
        return sendPost(url,nameValuePairList,null,requestPropertyMap,proxyHost,proxyPort);
    }
    public static HttpResponseResult proxySendPost(String url, String jsonParams, Map<String, Object> requestPropertyMap) {
        return sendPost(url,null,jsonParams,requestPropertyMap,proxyHost,proxyPort);
    }

    /**
     * 发送GET请求
     *
     * @param url               请求url
     * @param nameValuePairList 请求参数
     * @param requestPropertyMap 请求头
     * @return JSON或者字符串
     * @throws Exception
     */
    public static HttpResponseResult sendGet(String url, List<NameValuePair> nameValuePairList, Map<String, Object> requestPropertyMap,String proxyHost,int proxyPort) {
        HttpResponseResult httpResponseResult = new HttpResponseResult();
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            /*
             * 创建HttpClient对象
             */
            client = HttpClients.createDefault();
            /*
             * 创建URIBuilder
             */
//            log.info("https sendGet - {}", url);
            URIBuilder uriBuilder = new URIBuilder(url);
            /*
             * 设置参数
             */
            if (nameValuePairList != null) {
                uriBuilder.addParameters(nameValuePairList);
            }
            /*
             * 创建HttpGet
             */
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            if (proxyHost != null){
                HttpHost host = new HttpHost(proxyHost, proxyPort);
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000)
                        .setSocketTimeout(6000).setProxy(host).build();
                httpGet.setConfig(requestConfig);
                client = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
            }
            /*
             * 自定义请求头
             */
            for (Map.Entry<String, Object> map : requestPropertyMap.entrySet()) {
                httpGet.setHeader(new BasicHeader(map.getKey(), String.valueOf(map.getValue())));
            }
            /*
             * 请求服务
             */
            response = client.execute(httpGet);
            httpResponseResult.setResponse(response);
            String responseEntity = EntityUtils.toString(response.getEntity(),Constants.UTF8);
//            log.info("recv - "+responseEntity);
            /*
             * 获取响应吗
             */
            int statusCode = response.getStatusLine().getStatusCode();
            if (SUCCESS_CODE == statusCode) {
                httpResponseResult.setResponseEntity(responseEntity);
                return httpResponseResult;
            } else {
                log.error("HttpClientService-line: {}, errorMsg{}", 97, "GET请求失败！返回信息为"+responseEntity);
            }
        } catch (Exception e) {
            log.error("HttpClientService-line: {}, Exception: {}", 100, e);
        } finally {
            if (response != null){
                try {
                    client.close();
                    response.close();
                } catch (IOException e) {
                    log.error("CloseableHttpResponse: 关闭失败:{}", e);
                }
            }
        }
        return httpResponseResult;
    }

    /**
     * 发送POST请求
     *
     * @param url               请求url
     * @param nameValuePairList 请求参数
     * @param requestPropertyMap 请求头
     * @return JSON或者字符串
     * @throws Exception
     */
    public static HttpResponseResult sendPost(String url, List<NameValuePair> nameValuePairList, String jsonParams,
                                              Map<String, Object> requestPropertyMap,String proxyHost,int proxyPort) {
        HttpResponseResult httpResponseResult = new HttpResponseResult();
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            /*
             *  创建一个httpclient对象
             */
            client = HttpClients.createDefault();
            /*
             * 创建一个post对象
             */
//            log.info("https sendPost - {}", url);
            HttpPost post = new HttpPost(url);
            /*
             * 包装成一个Entity对象
             */
            if (nameValuePairList != null) {
                StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
                /*
                 * 设置请求的内容
                 */
                post.setEntity(entity);
            }
            if (jsonParams != null){
                log.info("请求的参数为:"+jsonParams);
                StringEntity entity = new StringEntity(jsonParams, "UTF-8");
                entity.setContentType("application/json");
                post.setEntity(entity);
            }
            if (proxyHost != null){
                HttpHost host = new HttpHost(proxyHost, proxyPort);
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000)
                        .setSocketTimeout(6000).setProxy(host).build();
                client = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
            }
            /*
             * 自定义请求头
             */
            for (Map.Entry<String, Object> map : requestPropertyMap.entrySet()) {
                post.setHeader(new BasicHeader(map.getKey(), String.valueOf(map.getValue())));
            }
            /*
             * 执行post请求
             */
            response = client.execute(post);
            httpResponseResult.setResponse(response);
            /*
             * 获取响应码
             */
            String responseEntity = EntityUtils.toString(response.getEntity(),Constants.UTF8);
//            log.info("recv - "+responseEntity);
            int statusCode = response.getStatusLine().getStatusCode();
            if (SUCCESS_CODE == statusCode) {
                httpResponseResult.setResponseEntity(responseEntity);
                return httpResponseResult;
            } else {
                log.error("HttpClientService-line: {}, errorMsg：{},请求返回: {}", 146, "POST请求失败！", responseEntity);
            }
        } catch (Exception e) {
            log.error("HttpClientService-line: {}, Exception：{}", 149, e);
        } finally {
            if (response != null){
                try {
                    client.close();
                    response.close();
                } catch (IOException e) {
                    log.error("CloseableHttpResponse: 关闭失败:{}", e);
                }
            }
        }
        return httpResponseResult;
    }

    public static String proxyHost ;
    public static int proxyPort ;

    //更新代理
    public static void updateProxy() {
       /* String url = "http://route.xiongmaodaili.com/xiongmao-web/api/glip?secret=94f3c0f5a558884dd8c7ddfb1a3ba0ec&orderNo=GL20210123123655wtZxKS3H&count=1&isTxt=1&proxyType=1";
        String result = HttpUtils.sendGet(url, null);
        log.info("代理更新为:"+result);
        String[] str = result.split(":");
        proxyHost = str[0];
        proxyPort = Integer.parseInt(str[1]);*/
    }
}
